import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { lastValueFrom } from 'rxjs';
import { Repository } from 'typeorm';
import { KitsService } from '../../modules/kits/kits.service';
import { TemplateService } from '../../modules/template/template.service';
import { FilesService } from '../../modules/files/files.service';

import { UserBehavior } from '../../modules/user-behavior/entities/user-behavior.entity';
import { UserInfoDto } from 'src/modules/model/dto/user-info.dto';

type ActionDefinition = {
  id: number | string;
  type: string;
  name: string;
  description: string;
};

type UnknownAction = {
  type: 'unknown';
  error: string;
};
@Injectable()
export class ChatSchemaService {
  constructor(
    private readonly kitsService: KitsService,
    private readonly templateService: TemplateService,
    private readonly filesService: FilesService,
    @InjectRepository(UserBehavior)
    private readonly userBehaviorRepository: Repository<UserBehavior>
  ) { }

    //判断是否新老用户
  async checkUserSchema(pageSize: number, user?: UserInfoDto): Promise<string> {
    const userBehaviorCount = await this.userBehaviorRepository.count({
      where: user ? { userId: user.id } : undefined
    });
    if (userBehaviorCount >= pageSize) {
      return this.oldUserSchema(pageSize, user);
    }
    return this.generateSchema(pageSize);
  }
  // 老用户schema
  async oldUserSchema(pageSize: number = 10, user?: UserInfoDto): Promise<string>  {
    const userBehaviorslist = await this.userBehaviorRepository.find({
      where: user ? { userId: user.id } : undefined,
      select: ['id', 'name','type', 'description','userId','createdAt'],
      take: pageSize,
      order: { createdAt: 'DESC' } 
    });
    const userBehaviors = userBehaviorslist
      .map(userBehaviors => this.createActionDefinition('Action', userBehaviors))
      .join('\n');

    const unknownDefinitions = this.getUnknownActionDefinition();
    const userBehaviorTypes = userBehaviorslist.map(userBehavior => `Action${userBehavior.name}`);

    const actionTypes = [...userBehaviorTypes, 'unknownAction'].join(' | ');
    return `export type Action = ${actionTypes};
${userBehaviors}
${unknownDefinitions}`;
  }
  // 新用户schema
  async generateSchema(pageSize: number = 10): Promise<string> {
    const [kits, templates, components] = await Promise.all([
      this.getKitDefinitions(pageSize),
      this.getTemplateDefinitions(pageSize),
      this.getComponentDefinitions(pageSize)
    ]);

    const unknownDefinitions = this.getUnknownActionDefinition();
    const actionTypes = await this.getActionTypes(pageSize);

    return this.combineSchemaDefinitions(
      kits,
      templates,
      components,
      unknownDefinitions,
      actionTypes
    );
  }
  //获取所有action
  private async getActionTypes(pageSize: number): Promise<string> {
    const [kits, templates, components] = await Promise.all([
      lastValueFrom(
        this.kitsService.findAll({ pageSize })
      ),
      lastValueFrom(
        this.templateService.findAll({ pageSize })
      ),
      lastValueFrom(
        this.filesService.findAll({ pageSize })
      ),
    ]);
    const kitTypes = kits.rows.map(kit => `Action${kit.name}`);

    const templateTypes = templates.rows.map(template => `Action${template.name}`);
    const componentTypes = components.rows.map(component => component.name);

    return [...kitTypes, ...templateTypes, ...componentTypes, 'unknownAction'].join(' | ');
  }
  //定义kit的action
  private async getKitDefinitions(pageSize: number): Promise<string> {
    const kits = await lastValueFrom(
      this.kitsService.findAll({ pageSize })
    );

    return kits.rows
      .map(kit => this.createActionDefinition('Action', kit))
      .join('\n');
  }
  //定义template的action
  private async getTemplateDefinitions(pageSize: number): Promise<string> {
    const templates = await lastValueFrom(
      this.templateService.findAll({ pageSize })
    );

    return templates.rows
      .map(template => this.createActionDefinition('Action', template))
      .join('\n');
  }
  //定义Component的action
  private async getComponentDefinitions(pageSize: number): Promise<string> {
    const components = await lastValueFrom(
      this.filesService.findAll({ pageSize })
    );
    return components.rows
      .map(component => `${component.content};`)
      .join('\n');
  }
    //定义unknown的action
  private getUnknownActionDefinition(): string {
    return `/**
* 兜底操作,适用于未匹配到其他action的场景;type是unknown时绝对不能返回reason
* 示例：
* - "创建撒大声地撒" →   {
    "type": "unknown",
    "error": "无法识别的用户请求: '撒大声地撒'"
  }
*/
export type unknownAction = {
    type: 'unknown';
    error: string;
};`;
  }
  // kit和template通用的action定义
  private createActionDefinition(prefix: string, entity: ActionDefinition): string {
    return `export type ${prefix}${entity.name} = {
    id: '${entity.id}';
    type: '${entity.type}';
    name: '${entity.name}';
    description: '${entity.description}';
};`;
  }
  // 组装最终schema
  private combineSchemaDefinitions(
    kitDefinitions: string,
    templateDefinitions: string,
    componentDefinitions: string,
    unknownDefinitions: string,

    actionTypes: string
  ): string {
    return `export type Action = ${actionTypes};
${kitDefinitions}
${templateDefinitions}
${componentDefinitions}
${unknownDefinitions}`;
  }


}

